export interface Result {
    name: string;
    content: string;
}

interface Get {
    result: Result;
    onsuccess: () => void;
    onerror: (reason?: any) => void;
}

interface Put {
    onsuccess: (target: { result: Result }) => void;
    onerror: (reason?: any) => void;
}

const SQL_NAME = "web-db";
const DB_NAME = "web";
let request: any;
let db: any;
let initPromise: Promise<any> | null = null;

// 初始化数据库
function init() {
    if (initPromise) {
        return initPromise;
    }

    initPromise = new Promise((resolve, reject) => {
        request = window.indexedDB.open(SQL_NAME);
        request.onerror = (event: any) => {
            reject(event);
            console.log("缓存获取失败");
        };
        request.onsuccess = (event: any) => {
            resolve(event.target.result);
            db = event.target.result;
        };
        request.onupgradeneeded = (event: any) => {
            db = event.target.result;
            let objectStore;
            if (!db.objectStoreNames.contains(DB_NAME)) {
                // 创建数据库
                objectStore = db.createObjectStore(DB_NAME, {
                    keyPath: "name",
                });
                objectStore.createIndex("content", "content", { unique: false }); // 建立索引
            }
        };
    });

    return initPromise;
}

// get操作，读取数据
export async function get(name: string): Promise<Result> {
    await init(); // 确保数据库已初始化
    return new Promise<Result>((resolve, reject) => {
        const select: Get = db
            .transaction([DB_NAME], "readonly")
            .objectStore(DB_NAME)
            .get(name);

        select.onsuccess = function () {
            resolve(select.result);
        };
        select.onerror = reject;
    });
}

// add操作，添加数据
export async function set(name: string, content: string): Promise<Result> {
    await init(); // 确保数据库已初始化
    return new Promise<Result>((resolve, reject) => {
        const select: Put = db
            .transaction([DB_NAME], "readwrite")
            .objectStore(DB_NAME)
            .add({ name: name, content });

        select.onsuccess = (event: any) => {
            resolve(event.target.result);
        };
        select.onerror = reject;
    });
}

// update操作，更新数据
export async function update(name: string, content: string): Promise<Result> {
    await init(); // 确保数据库已初始化
    return new Promise((resolve, reject) => {
        const select: Put = db
            .transaction([DB_NAME], "readwrite")
            .objectStore(DB_NAME)
            .put({ name, content });

        select.onsuccess = (event: any) => {
            resolve(event.target.result);
        };
        select.onerror = reject;
    });
}

// remove操作，删除数据
export async function remove(name: string): Promise<Result> {
    await init(); // 确保数据库已初始化
    return new Promise((resolve, reject) => {
        const select: Put = db
            .transaction([DB_NAME], "readwrite")
            .objectStore(DB_NAME)
            .delete(name);

        select.onsuccess = (event: any) => {
            resolve(event.target.result);
        };
        select.onerror = reject;
    });
}

// 导出 IndexDB 作为一个 Vue 插件
const IndexDB = {
    init,
    set,
    get,
    update,
    remove,
    // 添加 Vue 插件必需的 install 方法
    install(app: any) {
        // 自动初始化数据库
        init().catch(error => {
            console.error('Failed to initialize IndexDB:', error);
        });

        // 将 IndexDB 方法添加到全局属性中
        app.config.globalProperties.$indexDB = {
            init,
            set,
            get,
            update,
            remove
        };

        // 提供 provide/inject 功能
        app.provide('indexDB', {
            init,
            set,
            get,
            update,
            remove
        });
    }
};

export default IndexDB;
